#include "lvgl.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "my_font_40.h"
#include "plane_war.h"

// 声明图片资源
extern const lv_img_dsc_t fj1;     // 飞机图片
extern const lv_img_dsc_t dj2;     // 敌机图片
extern const lv_img_dsc_t zidan1;  // 子弹图片
extern const lv_img_dsc_t zidan1;  // 敌机子弹图片

/* 游戏常量定义 */
#define SCREEN_WIDTH      1024     // 屏幕宽度
#define SCREEN_HEIGHT     600      // 屏幕高度
#define PLANE_WIDTH       100      // 飞机宽度
#define PLANE_HEIGHT      70       // 飞机高度
#define BULLET_WIDTH      8        // 子弹宽度
#define BULLET_HEIGHT     20       // 子弹高度
#define ENEMY_WIDTH       100      // 敌机宽度
#define ENEMY_HEIGHT      87       // 敌机高度
#define BULLET_SPEED      20       // 玩家子弹速度
// #define ENEMY_SPEED       3        // 敌机速度
// #define ENEMY_BULLET_SPEED 8       // 敌机子弹速度
#define MAX_BULLETS       300      // 最大玩家子弹数量
#define MAX_ENEMY_BULLETS 100      // 最大敌机子弹数量
#define MAX_ENEMIES       10       // 最大敌机数量
#define PLAYER_MAX_HP     100     // 玩家最大生命值
#define HIT_DAMAGE        20      // 每次被击中的伤害值
#define HP_BAR_WIDTH      200     // 血条宽度
#define HP_BAR_HEIGHT     20      // 血条高度

/* 游戏对象结构体 */
typedef struct {
    lv_obj_t *obj;
    int x;
    int y;
    bool active;
} Bullet;

typedef struct {
    lv_obj_t *obj;
    int x;
    int y;
    bool active;
    int fire_cooldown;  // 射击冷却时间
} Enemy;

// 敌机子弹结构体
typedef struct {
    lv_obj_t *obj;
    int x;
    int y;
    bool active;
} EnemyBullet;

/* 游戏全局变量 */
static lv_obj_t *player_plane;
static int player_x = SCREEN_WIDTH / 2 - PLANE_WIDTH / 2;
static int player_y = SCREEN_HEIGHT - PLANE_HEIGHT - 20;
static Bullet bullets[MAX_BULLETS];
static Enemy enemies[MAX_ENEMIES];
static EnemyBullet enemy_bullets[MAX_ENEMY_BULLETS]; 
static int score = 0;
static lv_obj_t *score_label;
static lv_obj_t *score_display;     //分数显示
static bool game_running = false;   // 游戏运行状态
static bool game_paused = false;    // 游戏暂停状态
static lv_obj_t *game_over_window;  // 游戏结束窗口
static lv_obj_t *restart_btn;       // 继续游戏按钮
static lv_obj_t *quit_btn;          // 结束游戏按钮
static bool is_dragging = false;    // 滑动状态标记
static lv_obj_t *start_window;      // 开始窗口
static lv_obj_t *pause_window;      // 暂停窗口
static lv_obj_t *settings_window;   // 设置窗口
static lv_obj_t *pause_btn;         // 暂停按钮
static int bg_y1 = 0;               // 第一张背景图Y坐标
static int bg_y2 = -SCREEN_HEIGHT;  // 第二张背景图Y坐标（初始在屏幕上方）
static int bg_speed = 2;            // 背景滚动速度
static lv_obj_t *bg;                // 背景图片对象
static lv_obj_t *bg2;               // 背景图片2对象
static int player_hp = PLAYER_MAX_HP;  // 玩家当前生命值
static lv_obj_t *hp_bar;            // 进度条血条
static lv_obj_t *hp_label;          // 血量文字显示
static lv_obj_t *rank_window;       // 排名窗口
static lv_obj_t *rank_list_label;   // 排名列表显示标签
#define RANK_FILE_PATH "/lq/leitingzhanji/rank.dat"  // 排名文件路径
#define MAX_RANK_COUNT 5            // 最多保存5个排名
static int game_difficulty_level = 1;    // 初始难度等级（1级最易）
static uint32_t game_start_timestamp = 0;  // 游戏开始时的系统时间（ms）
static uint32_t game_accumulated_time = 0; // 累计游戏时长（ms）
static uint32_t game_running_time = 0;     // 当前总运行时长
static const uint32_t DIFFICULTY_UP_INTERVAL = 5000;  // 难度提升间隔（5秒）
//难度参数上限（避免难度过高）
static const int MAX_ENEMY_SPEED = 8;            // 敌机最大速度
static const int MAX_ENEMY_BULLET_SPEED = 15;    // 敌机子弹最大速度
static const int MIN_ENEMY_FIRE_COOLDOWN = 50;   // 敌机最小射击冷却
static const int MAX_ENEMY_SPAWN_RATE = 15;      // 敌机最大生成概率（%）
//动态难度参数（替换原有固定宏）
static int enemy_speed = 3;              // 敌机速度（初始值=原ENEMY_SPEED）
static int enemy_bullet_speed = 8;       // 敌机子弹速度（初始值=原ENEMY_BULLET_SPEED）
static int enemy_spawn_rate = 5;         // 敌机生成概率（初始5%，原rand()%100 < 5）
static int enemy_fire_cooldown_base = 150;// 敌机射击冷却基准（初始150帧，原rand()%150）

/* 初始化玩家子弹 */
static void init_bullets(void) {
    for (int i = 0; i < MAX_BULLETS; i++) {
        bullets[i].obj = lv_img_create(lv_scr_act());
        lv_image_set_src(bullets[i].obj, &zidan1);
        lv_obj_set_style_bg_opa(bullets[i].obj, LV_OPA_TRANSP, 0);
        lv_obj_set_style_border_width(bullets[i].obj, 0, 0);
        lv_obj_set_size(bullets[i].obj, BULLET_WIDTH, BULLET_HEIGHT);
        bullets[i].active = false;
        lv_obj_add_flag(bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 初始化敌机子弹 */
static void init_enemy_bullets(void) {
    for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
        enemy_bullets[i].obj = lv_img_create(lv_scr_act());
        lv_image_set_src(enemy_bullets[i].obj, &zidan1);  // 使用敌机子弹图片
        lv_obj_set_style_bg_opa(enemy_bullets[i].obj, LV_OPA_TRANSP, 0);
        lv_obj_set_style_border_width(enemy_bullets[i].obj, 0, 0);
        lv_obj_set_size(enemy_bullets[i].obj, BULLET_WIDTH, BULLET_HEIGHT);
        enemy_bullets[i].active = false;
        lv_obj_add_flag(enemy_bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 初始化敌机 */
static void init_enemies(void) {
    srand(time(NULL));
    for (int i = 0; i < MAX_ENEMIES; i++) {
        enemies[i].obj = lv_img_create(lv_scr_act());
        lv_img_set_src(enemies[i].obj, &dj2);
        lv_obj_set_style_bg_opa(enemies[i].obj, LV_OPA_TRANSP, 0);
        lv_obj_set_style_border_width(enemies[i].obj, 0, 0);
        lv_obj_set_size(enemies[i].obj, ENEMY_WIDTH, ENEMY_HEIGHT);
        enemies[i].active = false;
        enemies[i].fire_cooldown = rand() % 100;  // 初始化冷却时间
        lv_obj_add_flag(enemies[i].obj, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 发射玩家子弹 */
static void fire_bullet(void) {
    int offsets[] = {-42, -8, 0, 8, 42}; 
    int count = 0;
    
    for (int o = 0; o < 5; o++) {  
        for (int i = 0; i < MAX_BULLETS; i++) {
            if (!bullets[i].active) {
                bullets[i].x = player_x + PLANE_WIDTH / 2 - BULLET_WIDTH / 2 + offsets[o];
                bullets[i].y = player_y;
                lv_obj_set_pos(bullets[i].obj, bullets[i].x, bullets[i].y);
                bullets[i].active = true;
                lv_obj_clear_flag(bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
                count++;
                break;
            }
        }
        if (count <= o) break;
    }
}

/* 初始化进度条血条（使用lv_bar组件） */
static void init_hp_bar(void) {
    // 创建进度条容器
    lv_obj_t *hp_container = lv_obj_create(lv_scr_act());
    lv_obj_remove_flag(hp_container, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_size(hp_container, HP_BAR_WIDTH, HP_BAR_HEIGHT);
    lv_obj_set_style_bg_opa(hp_container, LV_OPA_TRANSP, 0);
    lv_obj_set_style_border_opa(hp_container, LV_OPA_TRANSP, LV_PART_MAIN);  // 边框完全透明
    lv_obj_set_style_border_width(hp_container, 0, 0);
    lv_obj_align(hp_container, LV_ALIGN_TOP_LEFT, 10, 50);

    // 创建进度条组件（lv_bar是专门的进度条组件）
    hp_bar = lv_bar_create(hp_container);
    lv_obj_set_size(hp_bar, HP_BAR_WIDTH, HP_BAR_HEIGHT);
    lv_bar_set_range(hp_bar, 0, PLAYER_MAX_HP);  // 设置范围
    lv_bar_set_value(hp_bar, PLAYER_MAX_HP, LV_ANIM_ON);  // 初始值
    lv_obj_align(hp_bar, LV_ALIGN_CENTER, 0, 0);

    // 配置进度条样式
    lv_obj_set_style_bg_color(hp_bar, lv_color_hex(0x333333), LV_PART_MAIN);  // 背景
    lv_obj_set_style_bg_color(hp_bar, lv_color_hex(0x00FF00), LV_PART_INDICATOR);  // 指示器
    lv_obj_set_style_border_width(hp_bar, 1, LV_PART_MAIN);
    lv_obj_set_style_border_color(hp_bar, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_obj_set_style_radius(hp_bar, 3, LV_PART_MAIN);

    // 血量文字标签
    hp_label = lv_label_create(hp_container);
    lv_label_set_text_fmt(hp_label, "%d/%d", player_hp, PLAYER_MAX_HP);
    lv_obj_set_style_text_color(hp_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(hp_label, &lv_font_montserrat_14, 0);
    lv_obj_align(hp_label, LV_ALIGN_CENTER, 0, 0);
}

/* 更新进度条血条 */
static void update_hp_bar(void) {
    // 进度条值更新，带动画效果
    lv_bar_set_value(hp_bar, player_hp, LV_ANIM_ON);
    
    // 更新血量文字
    lv_label_set_text_fmt(hp_label, "%d/%d", player_hp, PLAYER_MAX_HP);
    
    // 动态颜色变化
    lv_color_t color;
    if (player_hp > 70) {
        color = lv_color_hex(0x00FF00);  // 绿色
    } else if (player_hp > 30) {
        color = lv_color_hex(0xFFFF00);  // 黄色
    } else {
        color = lv_color_hex(0xFF0000);  // 红色
    }
    
    // 应用颜色
    lv_obj_set_style_bg_color(hp_bar, color, LV_PART_INDICATOR);
}

/* 玩家受到伤害 */
static void player_take_damage(int damage) {
    player_hp -= damage;
    if (player_hp < 0) player_hp = 0;
    
    update_hp_bar();  // 更新血条
    
    if (player_hp <= 0) {
        game_running = false;
        add_score_to_rank(score);
        lv_obj_clear_flag(game_over_window, LV_OBJ_FLAG_HIDDEN);
        char final_score[50];
        sprintf(final_score, "最终得分: %d", score);
        lv_label_set_text(score_display, final_score);
    }
}

/* 敌机发射子弹 */
static void enemy_fire_bullet(Enemy *enemy) {
    for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
        if (!enemy_bullets[i].active) {
            // 从敌机中心发射
            enemy_bullets[i].x = enemy->x + ENEMY_WIDTH / 2 - BULLET_WIDTH / 2;
            enemy_bullets[i].y = enemy->y + ENEMY_HEIGHT;
            lv_obj_set_pos(enemy_bullets[i].obj, enemy_bullets[i].x, enemy_bullets[i].y);
            enemy_bullets[i].active = true;
            lv_obj_clear_flag(enemy_bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
            break;
        }
    }
}

/* 生成敌机 */
static void spawn_enemy(void) {
    for (int i = 0; i < MAX_ENEMIES; i++) {
        if (!enemies[i].active) {
            enemies[i].x = rand() % (SCREEN_WIDTH - ENEMY_WIDTH);
            enemies[i].y = -ENEMY_HEIGHT;
            enemies[i].fire_cooldown = rand() % 100;  // 重置冷却时间
            lv_obj_set_pos(enemies[i].obj, enemies[i].x, enemies[i].y);
            enemies[i].active = true;
            lv_obj_clear_flag(enemies[i].obj, LV_OBJ_FLAG_HIDDEN);
            break;
        }
    }
}

/* 检查碰撞 */
static bool check_collision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {
    return (x1 < x2 + w2 &&
            x1 + w1 > x2 &&
            y1 < y2 + h2 &&
            y1 + h1 > y2);
}

/* 重置游戏状态（参数：is_return_to_main，标记是否返回主界面） */
static void reset_game(bool is_return_to_main) {
    // 若返回主界面，游戏运行状态设为false；若重新挑战，设为true
    game_running = is_return_to_main ? false : true; 
    game_paused = false;
    score = 0;                            // 重置分数
    player_hp = PLAYER_MAX_HP;            // 重置生命值
    game_start_timestamp = 0;             // 重置时间戳
    game_accumulated_time = 0;            // 重置累计时长
    game_difficulty_level = 1;            // 重置难度等级
    enemy_speed = 3;                      // 重置敌机速度
    enemy_bullet_speed = 8;               // 重置敌机子弹速度
    enemy_spawn_rate = 5;                 // 重置敌机生成概率
    enemy_fire_cooldown_base = 150;       // 重置敌机射击冷却
    
    lv_label_set_text(score_label, "得分 0");
    update_hp_bar();  // 更新血条显示
    
    player_x = SCREEN_WIDTH / 2 - PLANE_WIDTH / 2;
    player_y = SCREEN_HEIGHT - PLANE_HEIGHT - 20;
    lv_obj_set_pos(player_plane, player_x, player_y);
    
    // 重置所有子弹和敌机
    for (int i = 0; i < MAX_BULLETS; i++) {
        bullets[i].active = false;
        lv_obj_add_flag(bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
    }
    for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
        enemy_bullets[i].active = false;
        lv_obj_add_flag(enemy_bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
    }
    for (int i = 0; i < MAX_ENEMIES; i++) {
        enemies[i].active = false;
        enemies[i].fire_cooldown = rand() % 100;
        lv_obj_add_flag(enemies[i].obj, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 游戏进行 暂停按钮回调 */
static void pause_btn_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED && game_running && !game_paused) {
        game_paused = true;
        lv_obj_remove_flag(pause_window, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 游戏暂停 继续游戏按钮回调 */
static void resume_game_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        game_paused = false;
        lv_obj_add_flag(pause_window, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 游戏暂停 放弃关卡按钮回调 */
static void exit_game_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        lv_obj_add_flag(pause_window, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(start_window, LV_OBJ_FLAG_HIDDEN);
        reset_game(true); // 传递true：返回主界面，game_running设为false
    }
}

/* 游戏结束 重新挑战按钮回调 */
static void restart_game_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        reset_game(false); // 传递false：重新挑战，game_running设为true
        lv_obj_add_flag(game_over_window, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 游戏结束 结束关卡按钮回调 */
static void quit_game_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        // 传递true：返回主界面，game_running设为false
        reset_game(true); 
        lv_obj_add_flag(game_over_window, LV_OBJ_FLAG_HIDDEN);
        lv_obj_remove_flag(start_window, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 屏幕触摸事件处理 */
static void screen_touch_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    lv_indev_t *indev = lv_indev_get_act();

    if (!game_running || game_paused) {
        return;
    }

    static lv_point_t last_point;

    if (code == LV_EVENT_PRESSED) {
        lv_indev_get_point(indev, &last_point);
        is_dragging = true;
    }
    else if (code == LV_EVENT_RELEASED) {
        is_dragging = false;
    }
    else if (code == LV_EVENT_PRESSING && is_dragging) {
        lv_point_t curr_point;
        lv_indev_get_point(indev, &curr_point);
        
        int dx = curr_point.x - last_point.x;
        int dy = curr_point.y - last_point.y;
        
        player_x += dx;
        player_y += dy;
        
        if (player_x < 0) player_x = 0;
        if (player_x > SCREEN_WIDTH - PLANE_WIDTH) 
            player_x = SCREEN_WIDTH - PLANE_WIDTH;
        if (player_y < 0) player_y = 0;
        if (player_y > SCREEN_HEIGHT - PLANE_HEIGHT) 
            player_y = SCREEN_HEIGHT - PLANE_HEIGHT;
        
        lv_obj_set_pos(player_plane, player_x, player_y);
        last_point = curr_point;
    }
    else if (code == LV_EVENT_CLICKED) {
        fire_bullet();
    }
}

/* 自动发射子弹的定时器回调 */
static void auto_fire_timer(lv_timer_t *timer) {
    if (game_running && !game_paused) {
        fire_bullet();
    }
}

/* 开始游戏按钮回调函数 */
static void start_game_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        lv_obj_add_flag(start_window, LV_OBJ_FLAG_HIDDEN);
        game_running = true;
        game_paused = false;
    }
}

/* 创建暂停窗口 */
static void create_pause_window(void) {
    pause_window = lv_obj_create(lv_scr_act());
    lv_obj_set_size(pause_window, SCREEN_WIDTH, SCREEN_HEIGHT);
    lv_obj_set_style_bg_color(pause_window, lv_color_hex(0x000000), 0);
    lv_obj_set_style_bg_opa(pause_window, LV_OPA_70, 0);
    lv_obj_set_style_radius(pause_window, 0, 0);
    lv_obj_add_flag(pause_window, LV_OBJ_FLAG_HIDDEN);

    // 创建暂停标题
    lv_obj_t *title = lv_label_create(pause_window);
    lv_label_set_text(title, "游戏暂停");
    lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(title, &my_font_40, 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 150);
    
    // 创建按钮容器
    lv_obj_t *btn_container = lv_obj_create(pause_window);
    lv_obj_remove_flag(btn_container, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_size(btn_container, 500, 100);
    lv_obj_set_style_bg_opa(btn_container, LV_OPA_TRANSP, 0);
    lv_obj_set_style_border_width(btn_container, 0, 0);
    lv_obj_align(btn_container, LV_ALIGN_CENTER, 0, 50);
    
    // 创建继续游戏按钮
    lv_obj_t *resume_btn = lv_btn_create(btn_container);
    lv_obj_set_size(resume_btn, 200, 80);
    lv_obj_align(resume_btn, LV_ALIGN_RIGHT_MID, 0, 0);
    lv_obj_add_event_cb(resume_btn, resume_game_handler, LV_EVENT_CLICKED, NULL);
    
    // 继续游戏按钮文字
    lv_obj_t *resume_label = lv_label_create(resume_btn);
    lv_label_set_text(resume_label, "继续游戏");
    lv_obj_set_style_text_font(resume_label, &my_font_40, 0);
    lv_obj_center(resume_label);
    
    // 创建退出游戏按钮
    lv_obj_t *exit_btn = lv_btn_create(btn_container);
    lv_obj_set_size(exit_btn, 200, 80);
    lv_obj_align(exit_btn, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_add_event_cb(exit_btn, exit_game_handler, LV_EVENT_CLICKED, NULL);

    // 退出游戏按钮文字
    lv_obj_t *exit_label = lv_label_create(exit_btn);
    lv_label_set_text(exit_label, "放弃关卡");
    lv_obj_set_style_text_font(exit_label, &my_font_40, 0);
    lv_obj_center(exit_label);
}

/* 创建暂停按钮 */
static void create_pause_button(void) {
    pause_btn = lv_btn_create(lv_scr_act());
    lv_obj_set_size(pause_btn, 100, 40);
    lv_obj_align(pause_btn, LV_ALIGN_TOP_RIGHT, -10, 10);
    
    // 暂停按钮文字
    lv_obj_t *pause_label = lv_label_create(pause_btn);
    lv_label_set_text(pause_label, "暂停");
    lv_obj_set_style_text_font(pause_label, &my_font_40, 0);
    lv_obj_center(pause_label);

    lv_obj_add_event_cb(pause_btn, pause_btn_handler, LV_EVENT_CLICKED, NULL);
}

/* 创建游戏结束窗口 */
static void create_game_over_window(void) {
    // 创建游戏结束窗口（半透明遮罩）
    game_over_window = lv_obj_create(lv_scr_act());
    lv_obj_set_size(game_over_window, SCREEN_WIDTH, SCREEN_HEIGHT);
    lv_obj_set_style_bg_color(game_over_window, lv_color_hex(0x000000), 0);
    lv_obj_set_style_bg_opa(game_over_window, LV_OPA_70, 0); // 70%不透明度
    lv_obj_set_style_radius(game_over_window, 0, 0);
    lv_obj_add_flag(game_over_window, LV_OBJ_FLAG_HIDDEN); // 初始隐藏
    
    // 创建游戏结束标题
    lv_obj_t *title = lv_label_create(game_over_window);
    lv_label_set_text(title, "游戏结束!");
    lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(title, &my_font_40, 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 150);
    
    // 创建分数显示
    score_display = lv_label_create(game_over_window);
    lv_obj_set_style_text_color(score_display, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(score_display, &my_font_40, 0);
    lv_obj_align(score_display, LV_ALIGN_TOP_MID, 0, 220);
    
    // 创建按钮容器（用于对齐两个按钮）
    lv_obj_t *btn_container = lv_obj_create(game_over_window);
    lv_obj_remove_flag(btn_container, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_size(btn_container, 500, 100);
    lv_obj_set_style_bg_opa(btn_container, LV_OPA_TRANSP, 0); // 透明背景
    lv_obj_set_style_border_width(btn_container, 0, 0); // 无边框
    lv_obj_align(btn_container, LV_ALIGN_CENTER, 0, 50);
    
    // 创建重新挑战按钮
    restart_btn = lv_btn_create(btn_container);
    lv_obj_set_size(restart_btn, 200, 80);
    lv_obj_align(restart_btn, LV_ALIGN_RIGHT_MID, 0, 0);
    lv_obj_add_event_cb(restart_btn, restart_game_handler, LV_EVENT_CLICKED, NULL);
    
    // 重新挑战按钮文字
    lv_obj_t *restart_label = lv_label_create(restart_btn);
    lv_label_set_text(restart_label, "重新挑战");
    lv_obj_set_style_text_font(restart_label, &my_font_40, 0);
    lv_obj_center(restart_label);
    
    // 创建结束游戏按钮
    quit_btn = lv_btn_create(btn_container);
    lv_obj_set_size(quit_btn, 200, 80);
    lv_obj_align(quit_btn, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_add_event_cb(quit_btn, quit_game_handler, LV_EVENT_CLICKED, NULL);

    // 结束游戏按钮文字
    lv_obj_t *quit_label = lv_label_create(quit_btn);
    lv_label_set_text(quit_label, "结束关卡");
    lv_obj_set_style_text_font(quit_label, &my_font_40, 0);
    lv_obj_center(quit_label);
}

/* 设置按钮回调 */
static void settings_btn_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        lv_obj_remove_flag(settings_window, LV_OBJ_FLAG_HIDDEN);
    }
}

/* 设置窗口返回按钮回调 */
static void settings_back_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        lv_obj_add_flag(settings_window, LV_OBJ_FLAG_HIDDEN); // 隐藏设置窗口
    }
}

// 4个核心工具函数，负责文件读写、分数排序和去重（避免重复存储相同分数）、刷新排名列表
/* 工具函数1：读取本地排名文件，返回分数数组（已排序，降序）和实际分数个数 */
static int read_rank_file(int scores[], int max_count) {
    FILE *fp = fopen(RANK_FILE_PATH, "r");  // 只读方式打开文件
    if (fp == NULL)
    {
        perror("文件不存在1");
        return 0;  // 文件不存在则返回0个分数
    } 

    int count = 0;
    // 读取文件中所有分数（每行1个）
    while (count < max_count && fscanf(fp, "%d", &scores[count]) == 1) {
        count++;
    }
    fclose(fp);

    // 对分数进行降序排序（冒泡排序，简单高效）
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (scores[j] < scores[j + 1]) {
                int temp = scores[j];
                scores[j] = scores[j + 1];
                scores[j + 1] = temp;
            }
        }
    }

    // 去重（避免同一分数重复出现）
    int unique_count = 0;
    for (int i = 0; i < count; i++) {
        if (i == 0 || scores[i] != scores[unique_count - 1]) {
            scores[unique_count++] = scores[i];
        }
    }

    return unique_count;  // 返回去重后的有效分数个数
}

/* 工具函数2：将排序后的前N个分数写入本地文件 */
static void write_rank_file(int scores[], int count) {
    FILE *fp = fopen(RANK_FILE_PATH, "w");  // 覆盖写入（清空原有内容）
    if (fp == NULL)
    {
        perror("文件不存在2");
        return ;  
    } 

    // 只写入前MAX_RANK_COUNT个分数（最多5个）
    int write_count = count > MAX_RANK_COUNT ? MAX_RANK_COUNT : count;
    for (int i = 0; i < write_count; i++) {
        fprintf(fp, "%d\n", scores[i]);  // 每行1个分数
    }
    fclose(fp);
}

/* 工具函数3：游戏结束时，将当前分数加入排名并更新文件 */
static void add_score_to_rank(int current_score) {
    if (current_score <= 0) return;  // 分数<=0不加入排名

    int scores[MAX_RANK_COUNT + 1];  // 多留1个位置存当前分数
    int count = read_rank_file(scores, MAX_RANK_COUNT);  // 读取现有排名

    // 将当前分数加入数组（避免重复添加相同分数）
    bool is_duplicate = false;
    for (int i = 0; i < count; i++) {
        if (scores[i] == current_score) {
            is_duplicate = true;
            break;
        }
    }
    if (!is_duplicate) {
        scores[count++] = current_score;  // 追加当前分数
    }

    // 排序并保留前5名，更新文件
    int sorted_scores[MAX_RANK_COUNT + 1];
    memcpy(sorted_scores, scores, sizeof(int) * count);  // 复制分数数组
    // 降序排序
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (sorted_scores[j] < sorted_scores[j + 1]) {
                int temp = sorted_scores[j];
                sorted_scores[j] = sorted_scores[j + 1];
                sorted_scores[j + 1] = temp;
            }
        }
    }
    write_rank_file(sorted_scores, count);  // 写入前5名
}

/* 工具函数4：刷新排名列表（从文件读取最新排名并显示） */
static void refresh_rank_list(void) {
    int scores[MAX_RANK_COUNT];
    int count = read_rank_file(scores, MAX_RANK_COUNT);  // 读取最新排名

    char rank_data[200] = {0};  // 存储排名文本（足够容纳5个分数）
    if (count == 0) {
        // 无排名数据时显示提示
        strcpy(rank_data, " 暂无排名数据\n 快去创造记录吧！");
    } else {
        // 拼接排名文本（默认玩家名为“游客”）
        for (int i = 0; i < count; i++) {
            char line[50];
            sprintf(line, " %d. 游客   -   %d分\n", i + 1, scores[i]);
            strcat(rank_data, line);  // 追加到排名文本
        }
        // 不足5个排名时，用空行填充（保持窗口美观）
        for (int i = count; i < MAX_RANK_COUNT; i++) {
            strcat(rank_data, " \n");
        }
    }

    // 更新排名标签显示
    lv_label_set_text(rank_list_label, rank_data);
}

/* 排名窗口返回按钮回调 */
static void rank_back_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        lv_obj_add_flag(rank_window, LV_OBJ_FLAG_HIDDEN); // 隐藏排名窗口
    }
}

/* 查看排名按钮回调：显示排名窗口前先刷新最新数据 */
static void rank_btn_handler(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        refresh_rank_list();  // 每次打开排名窗口，都刷新最新排名
        lv_obj_remove_flag(rank_window, LV_OBJ_FLAG_HIDDEN);  // 显示排名窗口
    }
}

/* 创建排名窗口 */
static void create_rank_window(void) {
    // 1. 排名窗口主体（半透明遮罩）
    rank_window = lv_obj_create(start_window);  // 父容器为开始窗口，确保层级正确
    lv_obj_set_size(rank_window, SCREEN_WIDTH*3/4, SCREEN_HEIGHT*3/4);  // 窗口大小（屏幕3/4）
    lv_obj_set_style_bg_color(rank_window, lv_color_hex(0x000000), 0);   // 黑色背景
    lv_obj_set_style_bg_opa(rank_window, LV_OPA_80, 0);                  // 80%不透明度（半透明）
    lv_obj_center(rank_window);                                          // 窗口居中
    lv_obj_set_style_radius(rank_window, 5, 0);                          // 轻微圆角（可选）
    lv_obj_add_flag(rank_window, LV_OBJ_FLAG_HIDDEN);                    // 初始隐藏

    // 2. 排名窗口标题
    lv_obj_t *rank_title = lv_label_create(rank_window);
    lv_label_set_text(rank_title, "排行榜");
    lv_obj_set_style_text_color(rank_title, lv_color_hex(0xFFFF00), 0);   // 黄色标题（醒目）
    lv_obj_set_style_text_font(rank_title, &my_font_40, 0);               // 使用自定义字体
    lv_obj_align(rank_title, LV_ALIGN_TOP_MID, 0, 30);                   // 标题居上

    // 3. 排名列表显示标签（动态刷新）
    rank_list_label = lv_label_create(rank_window);
    lv_obj_set_style_text_color(rank_list_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(rank_list_label, &my_font_40, 0);
    lv_obj_set_width(rank_list_label, SCREEN_WIDTH*3/4 - 40);  // 留边距，避免文字溢出
    lv_obj_align(rank_list_label, LV_ALIGN_CENTER, 0, -20);
    refresh_rank_list();  // 初始加载时刷新排名

    // 4. 返回按钮（返回开始界面）
    lv_obj_t *rank_back_btn = lv_btn_create(rank_window);
    lv_obj_set_size(rank_back_btn, 120, 60);                                // 按钮大小
    lv_obj_align(rank_back_btn, LV_ALIGN_BOTTOM_MID, 0, -30);                // 按钮居下
    lv_obj_add_event_cb(rank_back_btn, rank_back_handler, LV_EVENT_CLICKED, NULL);  // 复用设置窗口的返回逻辑（隐藏当前窗口）

    // 返回按钮文字
    lv_obj_t *rank_back_label = lv_label_create(rank_back_btn);
    lv_label_set_text(rank_back_label, "返回");
    lv_obj_set_style_text_font(rank_back_label, &my_font_40, 0);
    lv_obj_center(rank_back_label);
}

/* 创建主界面窗口 */
static void create_start_window(void) {
    // 创建主界面窗口
    start_window = lv_obj_create(lv_screen_active());
    lv_obj_set_size(start_window, SCREEN_WIDTH, SCREEN_HEIGHT);
    lv_obj_set_pos(start_window, 0, 0);
    lv_obj_remove_flag(start_window, LV_OBJ_FLAG_SCROLLABLE);
    
    // 关键修改：清除所有可能的边框和背景
    lv_obj_set_style_pad_all(start_window, 0, LV_PART_MAIN); //去除窗口的内边距
    lv_obj_set_style_border_width(start_window, 0, LV_PART_MAIN);  // 去除边框宽度
    lv_obj_set_style_border_opa(start_window, LV_OPA_TRANSP, LV_PART_MAIN);  // 边框完全透明
    lv_obj_set_style_bg_opa(start_window, LV_OPA_TRANSP, LV_PART_MAIN);  // 背景完全透明
    
    // 设置背景图片
    lv_obj_t *bg1 = lv_image_create(start_window);
    lv_image_set_src(bg1, "A:/lq/xiangce/fengmian2.bmp");
    
    // 让图片充满整个父容器
    lv_obj_set_pos(bg1, 0, 0);
    lv_obj_set_size(bg1, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    // 创建开始按钮 透明状
    lv_obj_t *start_btn = lv_btn_create(start_window);
    lv_obj_set_size(start_btn, 135, 20);
    lv_obj_set_pos(start_btn, 445, 440);

    // 清除背景和边框
    lv_obj_set_style_pad_all(start_btn, 0, LV_PART_MAIN); 
    lv_obj_set_style_bg_opa(start_btn, LV_OPA_0, LV_STATE_DEFAULT);
    lv_obj_set_style_border_opa(start_btn, LV_OPA_0, LV_STATE_DEFAULT);
    lv_obj_set_style_border_width(start_btn, 0, LV_PART_MAIN);
    
    //创建设置按钮 透明状
    lv_obj_t *Settings_btn = lv_btn_create(start_window);
    lv_obj_set_size(Settings_btn, 60, 60);
    lv_obj_set_pos(Settings_btn, 378, 510);
    lv_obj_set_style_pad_all(Settings_btn, 0, LV_PART_MAIN); //去除内边距
    lv_obj_set_style_bg_opa(Settings_btn, LV_OPA_0, LV_STATE_DEFAULT);
    lv_obj_set_style_border_opa(Settings_btn, LV_OPA_0, LV_STATE_DEFAULT);
    lv_obj_set_style_border_width(Settings_btn, 0, LV_PART_MAIN);
    
    //创建查看排名按钮 透明状
    lv_obj_t *rank_btn = lv_btn_create(start_window);
    lv_obj_set_size(rank_btn, 120, 30);  // 按钮大小：根据背景图“查看排名”文字调整
    lv_obj_set_pos(rank_btn, 450, 510);  // 按钮位置：与设置按钮横向排列（可按需微调）
   
    lv_obj_set_style_pad_all(rank_btn, 0, LV_PART_MAIN); 
    lv_obj_set_style_bg_opa(rank_btn, LV_OPA_0, LV_STATE_DEFAULT);
    lv_obj_set_style_border_opa(rank_btn, LV_OPA_0, LV_STATE_DEFAULT);
    lv_obj_set_style_border_width(rank_btn, 0, LV_PART_MAIN); 
  
    // 绑定点击事件
    lv_obj_add_event_cb(rank_btn, rank_btn_handler, LV_EVENT_CLICKED, NULL);
    lv_obj_add_event_cb(start_btn, start_game_handler, LV_EVENT_CLICKED, NULL);
    lv_obj_add_event_cb(Settings_btn, settings_btn_handler, LV_EVENT_CLICKED, NULL);
}

// 音乐开关事件处理函数
static void music_switch_handler(lv_event_t *e) {
    lv_obj_t *switch_obj = lv_event_get_target(e);
    bool is_on = lv_obj_has_state(switch_obj, LV_STATE_CHECKED);
    
    if (is_on) {
        // 开启音乐
        // TODO: 实现开启音乐的逻辑
    } else {
        // 关闭音乐
        // TODO: 实现关闭音乐的逻辑
    }
}

// 音效开关事件处理函数
static void sound_switch_handler(lv_event_t *e) {
    lv_obj_t *switch_obj = lv_event_get_target(e);
    bool is_on = lv_obj_has_state(switch_obj, LV_STATE_CHECKED);
    
    if (is_on) {
        // 开启音效
        // TODO: 实现开启音效的逻辑
    } else {
        // 关闭音效
        // TODO: 实现关闭音效的逻辑
    }
}

/* 创建设置窗口 */
static void create_Settings_btn_window(void) {
    // 创建设置窗口（半透明遮罩）
    settings_window = lv_obj_create(start_window);
    lv_obj_set_size(settings_window, SCREEN_WIDTH*3/4, SCREEN_HEIGHT*3/4);
    lv_obj_set_style_bg_color(settings_window, lv_color_hex(0x000000), 0);
    lv_obj_set_style_bg_opa(settings_window, LV_OPA_70, 0); // 70%不透明度
    lv_obj_center(settings_window);
    lv_obj_set_style_radius(settings_window, 0, 0);
    lv_obj_add_flag(settings_window, LV_OBJ_FLAG_HIDDEN); // 初始隐藏
    
    // 创建用户名标题
    lv_obj_t *title = lv_label_create(settings_window);
    lv_label_set_text(title, "UID : LQ666");
    lv_obj_set_style_text_color(title, lv_color_hex(0x87CEEB), 0); //天蓝色
    lv_obj_set_style_text_font(title, &my_font_40, 0);
    lv_obj_align(title, LV_ALIGN_CENTER, 0, -180); 
    
    // 创建版本号标题
    lv_obj_t *title2 = lv_label_create(settings_window);
    lv_label_set_text(title2, "版本号: 1.0");
    lv_obj_set_style_text_color(title2, lv_color_hex(0x87CEEB), 0);
    lv_obj_set_style_text_font(title2, &my_font_40, 0);
    lv_obj_align(title2, LV_ALIGN_BOTTOM_MID, 0, 0); 

    // 创建音乐开关容器
    lv_obj_t *music_container = lv_obj_create(settings_window);
    lv_obj_remove_flag(music_container, LV_OBJ_FLAG_SCROLLABLE); //固定容器
    lv_obj_set_size(music_container, 400, 80);
    lv_obj_set_style_bg_opa(music_container, LV_OPA_0, 0); // 透明背景
    lv_obj_align(music_container, LV_ALIGN_CENTER, 0, -90);
    
    // 音乐开关标签
    lv_obj_t *music_label = lv_label_create(music_container);
    lv_label_set_text(music_label, "音乐");
    lv_obj_set_style_text_color(music_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(music_label, &my_font_40, 0);
    lv_obj_align(music_label, LV_ALIGN_LEFT_MID, 20, 0);
    
    // 音乐开关
    lv_obj_t *music_switch = lv_switch_create(music_container);
    lv_obj_set_size(music_switch, 100, 50);
    lv_obj_align(music_switch, LV_ALIGN_RIGHT_MID, -20, 0);
    lv_obj_add_event_cb(music_switch, music_switch_handler, LV_EVENT_VALUE_CHANGED, NULL);
    // 默认开启
    lv_obj_set_state(music_switch, LV_STATE_CHECKED, true);
    
    // 创建音效开关容器
    lv_obj_t *sound_container = lv_obj_create(settings_window);
    lv_obj_remove_flag(sound_container, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_size(sound_container, 400, 80);
    lv_obj_set_style_bg_opa(sound_container, LV_OPA_0, 0); // 透明背景
    lv_obj_align(sound_container, LV_ALIGN_CENTER, 0, 0);
    
    // 音效开关标签
    lv_obj_t *sound_label = lv_label_create(sound_container);
    lv_label_set_text(sound_label, "音效");
    lv_obj_set_style_text_color(sound_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_text_font(sound_label, &my_font_40, 0);
    lv_obj_align(sound_label, LV_ALIGN_LEFT_MID, 20, 0);
    
    // 音效开关
    lv_obj_t *sound_switch = lv_switch_create(sound_container);
    lv_obj_set_size(sound_switch, 100, 50);
    lv_obj_align(sound_switch, LV_ALIGN_RIGHT_MID, -20, 0);
    lv_obj_add_event_cb(sound_switch, sound_switch_handler, LV_EVENT_VALUE_CHANGED, NULL);
    // 默认开启
    lv_obj_set_state(sound_switch, LV_STATE_CHECKED, true);
    
    // 添加返回按钮
    lv_obj_t *back_btn = lv_btn_create(settings_window);
    lv_obj_set_size(back_btn, 100, 60);
    lv_obj_set_align(back_btn, LV_ALIGN_TOP_RIGHT); // 右上角
    lv_obj_add_event_cb(back_btn, settings_back_handler, LV_EVENT_CLICKED, NULL);
    
    // 返回按钮文字
    lv_obj_t *back_label = lv_label_create(back_btn);
    lv_label_set_text(back_label, "返回");
    lv_obj_set_style_text_font(back_label, &my_font_40, 0);
    lv_obj_center(back_label);
}

/* 更新背景滚动 */
static void update_background(void) {
    if (!game_running || game_paused) return;  // 游戏未运行或暂停时不滚动
    
    // 更新两张背景图的Y坐标
    bg_y1 += bg_speed;
    bg_y2 += bg_speed;
    
    // 当第一张背景图完全移出屏幕时重置位置
    if (bg_y1 >= SCREEN_HEIGHT) {
        bg_y1 = bg_y2 - SCREEN_HEIGHT;
    }
    
    // 当第二张背景图完全移出屏幕时重置位置
    if (bg_y2 >= SCREEN_HEIGHT) {
        bg_y2 = bg_y1 - SCREEN_HEIGHT;
    }
    
    // 应用新位置
    lv_obj_set_y(bg, bg_y1);
    lv_obj_set_y(bg2, bg_y2);
}

/* 更新游戏状态 */
static void update_game(lv_timer_t *timer) {
    if (!game_running || game_paused) return;  // 暂停时不更新游戏状态
    
    // 更新游戏时长和难度
    if (game_running && !game_paused) {
    // 游戏运行中且未暂停时才更新时间
    if (game_start_timestamp == 0) {
        // 记录游戏开始的时间戳
        game_start_timestamp = lv_tick_get();
    } else {
        // 计算当前运行时长（毫秒）
        uint32_t current_time = lv_tick_get();
        game_running_time = game_accumulated_time + (current_time - game_start_timestamp);
    }
    update_difficulty();                 // 检查是否需要提升难度
    } else if (game_running && game_paused) {
    // 游戏暂停时，累加已运行的时间并重置开始时间戳
    if (game_start_timestamp != 0) {
        game_accumulated_time += lv_tick_get() - game_start_timestamp;
        game_start_timestamp = 0;
    }
}
    
    // 更新背景滚动
    update_background();
    
    // 更新玩家子弹位置
    for (int i = 0; i < MAX_BULLETS; i++) {
        if (bullets[i].active) {
            bullets[i].y -= BULLET_SPEED;
            lv_obj_set_y(bullets[i].obj, bullets[i].y);
            
            // 子弹超出屏幕范围
            if (bullets[i].y < -BULLET_HEIGHT) {
                bullets[i].active = false;
                lv_obj_add_flag(bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
            }
        }
    }
    
    // 更新敌机子弹位置
    for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
        if (enemy_bullets[i].active) {
            enemy_bullets[i].y += enemy_bullet_speed;
            lv_obj_set_y(enemy_bullets[i].obj, enemy_bullets[i].y);
            
            // 子弹超出屏幕范围
            if (enemy_bullets[i].y > SCREEN_HEIGHT) {
                enemy_bullets[i].active = false;
                lv_obj_add_flag(enemy_bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
            }
        }
    }
    
    // 随机生成敌机
    if (rand() % 100 < enemy_spawn_rate) { // 5%的概率生成敌机
        spawn_enemy();
    }
    
    // 更新敌机位置并处理射击冷却
    for (int i = 0; i < MAX_ENEMIES; i++) {
        if (enemies[i].active) {
            enemies[i].y += enemy_speed;
            lv_obj_set_y(enemies[i].obj, enemies[i].y);
            
            // 减少冷却时间并在冷却结束后射击
            enemies[i].fire_cooldown--;
            if (enemies[i].fire_cooldown <= 0) {
                enemy_fire_bullet(&enemies[i]);
                // 重置冷却时间（随机值使攻击节奏变化）
                enemies[i].fire_cooldown = enemy_fire_cooldown_base;
            }
            
            // 敌机超出屏幕范围
            if (enemies[i].y > SCREEN_HEIGHT) {
                enemies[i].active = false;
                lv_obj_add_flag(enemies[i].obj, LV_OBJ_FLAG_HIDDEN);
            }
        }
    }
    
    // 碰撞检测 - 玩家子弹击中敌机
    for (int i = 0; i < MAX_BULLETS; i++) {
        if (bullets[i].active) {
            for (int j = 0; j < MAX_ENEMIES; j++) {
                if (enemies[j].active) {
                    if (check_collision(bullets[i].x, bullets[i].y, BULLET_WIDTH, BULLET_HEIGHT,
                                       enemies[j].x, enemies[j].y, ENEMY_WIDTH, ENEMY_HEIGHT)) {
                        // 击中敌机，销毁子弹和敌机
                        bullets[i].active = false;
                        lv_obj_add_flag(bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
                        
                        enemies[j].active = false;
                        lv_obj_add_flag(enemies[j].obj, LV_OBJ_FLAG_HIDDEN);
                        
                        // 加分
                        score += 10;
                        lv_label_set_text_fmt(score_label, "得分 %d", score);
                        lv_obj_set_style_text_font(score_label, &my_font_40, 0);
                    }
                }
            }
        }
    }
    
    // 修改敌机子弹击中玩家的碰撞检测
    for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
        if (enemy_bullets[i].active) {
            if (check_collision(
                enemy_bullets[i].x, enemy_bullets[i].y, BULLET_WIDTH, BULLET_HEIGHT,
                player_x + 5, player_y + 5, PLANE_WIDTH - 10, PLANE_HEIGHT - 10
            )) {
                // 玩家被击中，扣除生命值
                enemy_bullets[i].active = false;
                lv_obj_add_flag(enemy_bullets[i].obj, LV_OBJ_FLAG_HIDDEN);
                
                player_take_damage(HIT_DAMAGE);  // 调用扣血函数
            }
        }
    }

    // 修改敌机碰撞玩家的碰撞检测
    for (int i = 0; i < MAX_ENEMIES; i++) {
        if (enemies[i].active) {
            if (check_collision(
                player_x + 5, player_y + 5, 
                PLANE_WIDTH - 10, PLANE_HEIGHT - 10,
                enemies[i].x + 5, enemies[i].y + 5, 
                ENEMY_WIDTH - 10, ENEMY_HEIGHT - 10
            )) {
                // 敌机碰撞玩家，扣除更多生命值
                enemies[i].active = false;
                lv_obj_add_flag(enemies[i].obj, LV_OBJ_FLAG_HIDDEN);
                
                player_take_damage(HIT_DAMAGE * 2);  // 碰撞伤害更高
            }
        }
    }
}

/* 动态更新游戏难度（基于系统时间戳，精准统计运行时长） */
static void update_difficulty(void) {
    // 仅游戏运行中（非暂停、非主界面）才更新难度
    if (!game_running || game_paused) {
        // 暂停时记录已累计时长，恢复时从当前时间重新开始
        if (game_running && game_paused && game_start_timestamp != 0) {
            game_accumulated_time += lv_tick_get() - game_start_timestamp;
            game_start_timestamp = 0; // 暂停时重置开始时间戳
        }
        return;
    }

    // 游戏开始/恢复时，记录当前系统时间戳
    if (game_start_timestamp == 0) {
        game_start_timestamp = lv_tick_get();
    }

    // 计算当前真实运行时长：累计时长 + 本次运行时长
    uint32_t current_run_time = lv_tick_get() - game_start_timestamp;
    uint32_t total_running_time = game_accumulated_time + current_run_time;

    // 计算当前应有的难度等级（每30秒升1级）
    uint32_t target_level = (total_running_time / DIFFICULTY_UP_INTERVAL) + 1;
    if (target_level == game_difficulty_level) return; // 难度未变化，直接返回

    // 更新难度等级
    game_difficulty_level = target_level;
    LV_LOG_USER("难度提升至 %d 级！", game_difficulty_level);

    // 调整难度参数
    enemy_speed = 3 + (game_difficulty_level - 1) * 1;
    if (enemy_speed > MAX_ENEMY_SPEED) enemy_speed = MAX_ENEMY_SPEED;

    enemy_spawn_rate = 5 + (game_difficulty_level - 1) * 2;
    if (enemy_spawn_rate > MAX_ENEMY_SPAWN_RATE) enemy_spawn_rate = MAX_ENEMY_SPAWN_RATE;

    enemy_bullet_speed = 8 + (game_difficulty_level - 1) * 1;
    if (enemy_bullet_speed > MAX_ENEMY_BULLET_SPEED) enemy_bullet_speed = MAX_ENEMY_BULLET_SPEED;

    enemy_fire_cooldown_base = 150 - (game_difficulty_level - 1) * 10;
    if (enemy_fire_cooldown_base < MIN_ENEMY_FIRE_COOLDOWN) enemy_fire_cooldown_base = MIN_ENEMY_FIRE_COOLDOWN;
}

/* 初始化游戏 */
void plane_war_init(void) {
    lv_obj_remove_flag(lv_scr_act(), LV_OBJ_FLAG_SCROLLABLE); //锁定活动屏幕 让其不能滑动
    
    // 设置地图背景（两张一样的图片无缝滚动，图片必须要求上下边缘可以无缝连接）
    bg = lv_image_create(lv_scr_act());
    lv_image_set_src(bg, "A:/lq/xiangce/map2.bmp");
    lv_obj_set_size(bg, SCREEN_WIDTH, SCREEN_HEIGHT);
    lv_obj_set_pos(bg, 0, bg_y1);

    // 创建第二张背景图用于无缝滚动
    bg2 = lv_image_create(lv_scr_act());
    lv_image_set_src(bg2, "A:/lq/xiangce/map2.bmp");
    lv_obj_set_size(bg2, SCREEN_WIDTH, SCREEN_HEIGHT);
    lv_obj_set_pos(bg2, 0, bg_y2);
    
    // 创建玩家飞机
    player_plane = lv_image_create(lv_scr_act());
    //lv_gif_set_src(player_plane, "A:/lq/xiangce/fj4.gif"); //使用带透明通道的PNG图片（无背景的图形）
    lv_image_set_src(player_plane, &fj1);

    lv_obj_set_style_bg_opa(player_plane, LV_OPA_TRANSP, LV_PART_MAIN);  // 背景全透明
    lv_obj_set_style_border_width(player_plane, 0, LV_PART_MAIN);        // 边框宽度设为 0
    lv_obj_set_style_border_opa(player_plane, LV_OPA_TRANSP, LV_PART_MAIN);  // 边框全透明
    lv_obj_set_style_outline_width(player_plane, 0, LV_PART_MAIN);       // 清除外边框（若有）

    lv_obj_set_size(player_plane, PLANE_WIDTH, PLANE_HEIGHT); // 设置飞机尺寸
    player_x = SCREEN_WIDTH / 2 - PLANE_WIDTH / 2;
    player_y = SCREEN_HEIGHT - PLANE_HEIGHT - 20;
    lv_obj_set_pos(player_plane, player_x, player_y);
    
    // 创建分数标签
    score_label = lv_label_create(lv_scr_act());
    lv_label_set_text(score_label, "得分 0");
    lv_obj_set_style_text_color(score_label, lv_color_hex(0x0066CC), 0); //经典蓝
    lv_obj_set_style_text_font(score_label, &my_font_40, 0);
    lv_obj_align(score_label, LV_ALIGN_TOP_LEFT, 10, 10);
    
    // 初始化子弹和敌机
    init_bullets();
    init_enemy_bullets();  // 初始化敌机子弹
    init_enemies();

    //初始化血条
    init_hp_bar();
    
    // 创建游戏结束窗口
    create_game_over_window();
    
    // 创建暂停窗口和暂停按钮
    create_pause_window();
    create_pause_button();

    // 绑定事件：整个屏幕监听触摸事件
    lv_obj_add_event_cb(lv_scr_act(), screen_touch_handler, LV_EVENT_ALL, NULL);
    
    // 创建游戏更新定时器 (17ms更新一次，约60FPS)
    lv_timer_create(update_game, 17, NULL);
    
    // 创建自动发射子弹定时器 (120ms发射一次)
    lv_timer_create(auto_fire_timer, 120, NULL);
    
    // 创建并显示主界面窗口
    create_start_window();

    // 创建设置窗口
    create_Settings_btn_window();
    
    //创建排名窗口
    create_rank_window();
}
